package itsm.isperp.framework.upload.impl;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.UploadInfo;
import itsm.isperp.framework.service.IInstanceService;
import itsm.isperp.framework.upload.FilePersister;
import itsm.isperp.framework.utils.FileUploadUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;

public class DirectoryUploadPersister implements FilePersister {

	private String store;

	/*
	 * (non-Javadoc)
	 * 
	 * @see itsm.isperp.upload.FilePersister#persist(java.io.InputStream)
	 */
	@Override
	public File persist(InputStream inputStream, UploadInfo uploadInfo)
			throws IOException {

		return FileUploadUtils.persist(inputStream, uploadInfo);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see itsm.isperp.upload.FilePersister#get(java.lang.String)
	 */
	@Override
	public InputStream get(String id) throws IOException {
		String fileStore = store.substring(5);
		File fileDir = new File(fileStore);
		if (!fileDir.exists()) {
			IInstanceService instanceService = ContextHolder
					.getSpringBean(IInstanceService.SERVICE_ID);
			String projectRootPath = instanceService.getAppRootPath();
			fileStore = projectRootPath + File.separator + fileStore;
		}
		File file = new File(fileStore);
		File destFile = new File(file, id);
		boolean isExists = destFile.exists();
		Assert.isTrue(isExists,
				String.format("被读取的文件[%s]未找到", destFile.getAbsolutePath()));
		InputStream inputStream = FileUtils.openInputStream(destFile);
		return inputStream;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see itsm.isperp.upload.FilePersister#delete(java.lang.String)
	 */
	@Override
	public void delete(String id) throws IOException {
		String fileStore = store.substring(5);
		File fileDir = new File(fileStore);
		if (!fileDir.exists()) {
			IInstanceService instanceService = ContextHolder
					.getSpringBean(IInstanceService.SERVICE_ID);
			String projectRootPath = instanceService.getAppRootPath();
			fileStore = projectRootPath + File.separator + fileStore;
		}
		File file = new File(fileStore);
		File destFile = new File(file, id);
		boolean isExists = destFile.exists();
		Assert.isTrue(isExists,
				String.format("将被删除的文件[%s]未找到", destFile.getAbsolutePath()));
		destFile.delete();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see itsm.isperp.upload.FilePersister#support(java.lang.String)
	 */
	@Override
	public boolean support(String store) {
		if (store.startsWith("file:"))
			return true;
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see itsm.isperp.upload.FilePersister#setStore(java.lang.String)
	 */
	@Override
	public void setStore(String store) {
		this.store = store;
	}

}
